/**
 * 重置坐骑经验值脚本
 * 修复坐骑经验值超出数据库范围的问题
 */

const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
  host: '43.143.253.188',
  user: 'nextjs',
  password: 'yEAiRE2jcxTyRBy5',
  database: 'nextjs',
  charset: 'utf8mb4'
};

async function resetMountExperience () {
  let connection;

  try {
    console.log('🔌 连接数据库...');
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功');

    // 查看当前坐骑经验值
    console.log('🔍 查看当前坐骑经验值...');
    const [rows] = await connection.execute(
      'SELECT id, characterId, level, experience FROM character_mounts WHERE characterId = 2001'
    );

    console.log('📊 当前坐骑数据:');
    rows.forEach((mount, index) => {
      console.log(`  ${index + 1}. 坐骑ID: ${mount.id} (等级: ${mount.level}, 经验: ${mount.experience})`);
    });

    // 重置坐骑经验值
    console.log('🔄 重置坐骑经验值...');
    await connection.execute(
      'UPDATE character_mounts SET experience = 0, level = 1 WHERE characterId = 2001'
    );
    console.log('✅ 坐骑经验值已重置');

    // 重置训练记录
    console.log('🔄 重置训练记录...');
    await connection.execute(
      'UPDATE mount_training SET dailyCount = 0, totalExperience = 0 WHERE characterId = 2001'
    );
    console.log('✅ 训练记录已重置');

    // 查看训练记录
    console.log('🔍 查看训练记录...');
    const [trainingRows] = await connection.execute(
      'SELECT characterId, dailyCount, totalExperience FROM mount_training WHERE characterId = 2001'
    );

    console.log('📊 训练记录数据:');
    trainingRows.forEach((record, index) => {
      console.log(`  ${index + 1}. 角色ID: ${record.characterId} (每日次数: ${record.dailyCount}, 总经验: ${record.totalExperience})`);
    });

    // 验证重置结果
    console.log('🔍 验证重置结果...');
    const [newRows] = await connection.execute(
      'SELECT id, characterId, level, experience FROM character_mounts WHERE characterId = 2001'
    );

    console.log('📊 重置后的坐骑数据:');
    newRows.forEach((mount, index) => {
      console.log(`  ${index + 1}. 坐骑ID: ${mount.id} (等级: ${mount.level}, 经验: ${mount.experience})`);
    });

    console.log('🎉 坐骑经验值重置完成！');

  } catch (error) {
    console.error('❌ 重置坐骑经验值失败:', error.message);
    throw error;
  } finally {
    if (connection) {
      await connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }
}

// 运行脚本
if (require.main === module) {
  resetMountExperience().catch((error) => {
    console.error('💥 脚本执行失败:', error.message);
    process.exit(1);
  });
}

module.exports = { resetMountExperience };
